<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<style>
	.tdBorder td{border:none;padding: 4px 2px;}
	.tw{width:190px;}
	/*select*/
.select_box{ position:relative; padding:0 24px 0 0; width:120px; text-align:left;}
.select_txt{ float:left; padding-left:2px; width:100%; height:22px; line-height:22px; border:1px solid #ccc;}
.select_btn{ display:block; position:absolute; right:0; top:0; width:24px; height:24px; cursor:pointer; background:url(../images/select_btn.png) no-repeat;}
.select_close{ display:none; position:absolute; right:28px; top:8px; width:9px; height:9px; cursor:pointer; background:url(../images/select_close.png) no-repeat;}

.select_con{ display:none; position:absolute; top:25px; left:0; z-index:1000; width:99.5%; max-height:150px; border:1px solid #177dba; overflow-y:auto; background:#fff;}
.select_con p{ clear:both; padding:0 10px; line-height:26px; cursor:pointer;}
.select_con p:hover{ background:#e7ebee;}

.t_con{margin:150px auto; width:500px; border:1px solid #ccc; background:#fff;}
</style>
<body>
<form id="thisForm" name="thisForm" action="" method="post" class="bs-docs-example form-inline">
<input type="hidden" id="parentAddressCode" value="000000000000">
<input type="hidden" id="codeLevel" value="">
<input type="hidden" id="provinceCode" name="海南省" value="460000000000">
<input type="hidden" id="cityCode" name="" value="">
<input type="hidden" id="countyCode" name="" value="">
<input type="hidden" id="townCode" name="" value="">
<input type="hidden" id="villageCode" name="" value="">
<input type="hidden" id="naturalVillageCode" name="" value="">
<input type="hidden" id="addressCode"> 
<input type="hidden" id="addressName">
<table class="c_table m_t10 tdBorder" >
	<tr>
		<td width="55px">省</td>
		<td class="t_w">
			<div class="select_box" id="provinceName"><input type="text" value="海南省" class="select_txt" onclick="find('#provinceName','#provinceCode','#province_div',0,'#pImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#provinceCode"></i><i class="select_btn" data-role="select_btn" ></i>
                <div class="select_con" data-role="option_con">
                </div>
              </div>
         </td>
		<td width="55px">市 </td>
		<td>
			<div class="select_box" id="cityName"><input type="text" class="select_txt" onkeyup="check('#cityName','#city_div',1 , this)" onclick="find('#cityName','#cityCode','#city_div',1,'#cityImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#cityCode" ></i><i class="select_btn" data-role="select_btn"></i>
                <div class="select_con" data-role="option_con">
                </div>
            </div>
		<td width="55px">县</td>
		<td>
			<div class="select_box" id="countyName"><input type="text" class="select_txt" onkeyup="check('#countyName','#county_div',2 , this)" onclick="find('#countyName','#countyCode','#county_div',2,'#cImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#countyCode"></i><i class="select_btn" data-role="select_btn"></i>
                <div class="select_con" data-role="option_con">
                </div>
            </div>
        </td>
	</tr>
	<tr >
		<td></td><td id="province_div"></td><td></td>
		<td></td><td id="city_div"></td><td></td>
		<td></td><td id="county_div"></td><td></td>
	</tr>
	<tr>
		<td width="55px">乡镇</td>
		<td>
			<div class="select_box" id="townName"><input type="text" class="select_txt" onkeyup="check('#townName','#town_div',3 , this)" onclick="find('#townName','#townCode','#town_div',3,'#tImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#townCode"></i><i class="select_btn" data-role="select_btn"></i>
                <div class="select_con" data-role="option_con">
                </div>
            </div>
        </td>
		<td width="55px">村</td>
		<td>
			<div class="select_box" id="villageName"><input type="text" class="select_txt" onkeyup="check('#villageName','#village_div',4 , this)" onclick="find('#villageName','#villageCode','#village_div',4,'#vImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#villageCode"></i><i class="select_btn" data-role="select_btn"></i>
                <div class="select_con" data-role="option_con">
                </div>
            </div>
         </td>
		<td width="55px">自然村</td>
		<td>
			<div class="select_box" id="naturalVillageName"><input type="text" class="select_txt" onkeyup="check('#naturalVillageName','#naturalVillage_div',5 , this)" onclick="find('#naturalVillageName','#naturalVillageCode','#naturalVillage_div',5,'#nImg' , this)" data-role="select_txt"><i class="select_close" data-role="select_close" zz="#naturalVillageCode"></i><i class="select_btn" data-role="select_btn"></i>
                <div class="select_con" data-role="option_con">
                </div>
            </div>
	</tr>
	<tr>
		<td></td><td id="town_div"></td><td></td>
		<td></td><td id="village_div"></td><td></td>
		<td></td><td id="naturalVillage_div"></td><td></td>
	</tr>
</table>
</form>
	<script type="text/javascript">
		
		/**
		*	当获取焦点
		*/
		/* function getFocus(obj , img){
			$(img).show();
		}  */
		//区划代码层级（0.省、1.市、2.县、3.乡镇、4.村、5.自然村）
		var codeLevel = null;
		//省份名称
		var provinceName = null;
		//市名称
		var cityName = null;
		//县名称
		var countyName = null;
		//乡镇名称
		var townName = null;
		//村名称
		var villageName = null;
		//自然村名称
		var naturalVillageName = null;
		//父级代码
		var parentCode = null;
		//ajax请求返回数据
		var data_ = null;
		//高亮的索引 
		var highLightIndex = -1;
		// 超时的标识（对用户连续快速按下键盘的事件做延时处理，只对用户在500ms内最后一次请求，让其生效）
		var timeoutId;
		$(document).ready(function() {
			//窗口设置非DIV弹出层点击，隐藏DIV弹出层
			$(document).bind("click", function(e) {
				highLightIndex = -1;
				var target = $(e.target);
				if (target.closest(".popWindow").length == 0) {
					$(".popWindow").hide();
				}
			});
			//省份变动，所有输入重置
			$('#provinceName').change(function() {
				$("input[name='handInput']").val("");
			});
		});
		
		//点击下拉框，下拉弹出层回车选择等操作后，需要重新赋值
		function reBuild(dicAddress, codeLevel ,  obj) {
			obj = $(obj).parent().parent().parent().parent().parent().parent().parent();
			
			
			//obj.find('#addressCode').val(dicAddress.addressCode);
			//obj.find('#addressName').val(dicAddress.addressName);
			$(obj).find('#provinceCode').attr("name",dicAddress.provinceName);
			$(obj).find('#provinceName').find(".select_txt").attr("value",dicAddress.provinceName);
			$(obj).find('#provinceCode').attr("value",dicAddress.provinceCode);
			$(obj).find('#cityCode').attr("name",dicAddress.cityName);
			$(obj).find('#cityName').find(".select_txt").attr("value",dicAddress.cityName);
			$(obj).find("#cityCode").attr("value",dicAddress.cityCode);
			$(obj).find("#countyCode").attr("name",dicAddress.countyName);
			$(obj).find('#countyName').find(".select_txt").attr("value",dicAddress.countyName);
			$(obj).find("#countyCode").attr("value",dicAddress.countyCode);
			$(obj).find('#townCode').attr("name",dicAddress.townName);
			$(obj).find('#townName').find(".select_txt").attr("value",dicAddress.townName);
			$(obj).find('#townCode').attr("value",dicAddress.townCode);
			$(obj).find('#villageCode').attr("name",dicAddress.villageName);
			$(obj).find('#villageName').find(".select_txt").attr("value",dicAddress.villageName);
			$(obj).find('#villageCode').attr("value",dicAddress.villageCode);
			$(obj).find('#naturalVillageCode').attr("name",dicAddress.naturalVillageName);
			$(obj).find('#naturalVillageName').find(".select_txt").attr("value",dicAddress.naturalVillageName);
			$(obj).find('#naturalVillageCode').attr("value",dicAddress.naturalVillageCode);
			
			var	selectClose  = $(obj).find('[data-role="select_close"]');
			
			$(selectClose).each(function(){
				if($(this).siblings(".select_txt").val()!="" && $(this).siblings(".select_txt").val()!=undefined){
					$(this).show();
				}
			});
			
		}
		
		//获取键盘弹起事件
		function check(inputName, divName, level , obj) {
			codeLevel = level;
			thisObj =$(obj).parent().parent().parent().parent().parent().parent();
			//判断是否选择省份，省份为必选项，其后任何操作建立于省份已选择
			if (thisObj.find("#provinceName").find(".select_txt").val()== "") {
				alert("请先选择省份！");
				thisObj.find("input[name=handInput]").val("");
				return false;
			}
			processKeyup(inputName, divName, codeLevel , thisObj);
		}

		//下拉按钮点击事件
		function find(inputName,codeName, divName, level , img , thisObj) {
			obj = $(thisObj).parent().parent().parent().parent().parent().parent();
			//init();
			codeLevel = level;
			//同上，需要选择省份
			if (inputName != "#provinceName") {
				if (obj.find("#provinceName").find(".select_txt") == "") {
					alert("请先选择省份！");
					$("input[name=handInput]").val("");
					return false;
				}
			}
			//根据代码层级，给予父级代码赋值，赋值依据为，上一级的所选CODE
			parentCode = $("#parentAddressCode").val();
			if (codeLevel == 1) {
				parentCode = obj.find('#provinceCode').val();
			} else if (codeLevel == 2) {
				parentCode = obj.find('#cityCode').val();
			} else if (codeLevel == 3) {
				parentCode =obj.find('#countyCode').val();
			} else if (codeLevel == 4) {
				parentCode = obj.find('#townCode').val();
			} else if (codeLevel == 5) {
				parentCode =obj.find('#villageCode').val();
			}
			ajaxRequestForLevelSearch(inputName,codeName, divName, codeLevel, parentCode, img , thisObj);
		}

		//点击下拉图标，ajax请求后台数据
		function ajaxRequestForLevelSearch(inputName,codeName, divName, codeLevel,parentCode, img , obj) {
			$.ajax({
				type : "post", // http请求方法,默认:"post"
				url : "${ctx}/addressSelect/listByParent", // 发送请求的地址
				data : "parentAddressCode=" + parentCode+"&CSRFToken=${csrfToken}", //参数为父级代码
				dataType : "json", // 预期服务器返回的数据类型
				success : function(data) {
					var dataObj = eval("(" + data + ")");//转换为json对象 
					data_ = dataObj.dataList;
					if (data_ == null || data_.length <= 0) {
						return;
					}
					var word_div='' ;
					$thisObj=$(obj).parent().find(".select_con");
					$thisObj.empty();
					for (var i = 0; i < data_.length; i++) {
						//循环根据每条数据添加DIV，赋值为addressName
						$thisObj.append('<p id="'+data_[i].addressCode+'">'+data_[i].addressName+'</p>');
					}
					$(obj).parent().find(".select_con").show();
					
					$(obj).parent().find(".select_con").find('p').click(function(){
					$(obj).parent().find(".select_txt").attr("value",($(this).html()));
					$(obj).parent().find('[data-role="select_close"]').show();
					
					$(obj).parent().parent().parent().parent().parent().parent().find(codeName).attr("value",$(this).attr("id"));
					$(obj).parent().parent().parent().parent().parent().parent().find(codeName).attr("name",$(this).html());
					
					
					$(obj).parent().find(".select_con").empty();
					$(obj).parent().find(".select_con").hide();
						
					});
				}
			});
		}
		

		/**
		 * 根据回车按钮，进行模糊查询AJAX请求
		 */
		function processAjaxRequest(inputName, divName, codeLevel , obj) {
			
			$.ajax({
				type : "post", // http请求方法,默认:"post"
				url : "${ctx}/addressSelect/searchData", // 发送请求的地址
				data : "keyword=" + $.trim($(inputName).val()) + "&codeLevel="
						+ codeLevel + "&provinceName=" + provinceName
						+ "&cityName=" + cityName + "&countyName=" + countyName
						+ "&townName=" + townName + "&villageName="
						+ villageName + "&naturalVillageName="
						+ naturalVillageName+"&CSRFToken=${csrfToken}",
				dataType : "json", // 预期服务器返回的数据类型
				success : function(data) {
					$(obj).find(divName).html('').show();
					var dataObj = eval("(" + data + ")");//转换为json对象 
					data_ = dataObj.dataList;
					if (data_ == null || data_.length <= 0) {
						return;
					}
					for (var i = 0; i < data_.length; i++) {
						
						var temp=$('<p></p>');
						//因为模糊查询，需要显示市 - 县 - 乡镇 - 村、、、、、这种完全展示的效果，需要进行name拼接
						var innerHtml = data_[i].cityName;
						if (codeLevel == 2) {
							innerHtml = data_[i].cityName + " "
									+ data_[i].countyName;
							//obj.find(divName).width(obj.find(inputName).width() * codeLevel);
						} else if (codeLevel == 3) {
							innerHtml = data_[i].cityName + " "
									+ data_[i].countyName + " "
									+ data_[i].townName;
							//obj.find(divName).width(obj.find(inputName).width() * codeLevel);
						} else if (codeLevel == 4) {
							innerHtml = data_[i].cityName + " "
									+ data_[i].countyName + " "
									+ data_[i].townName + " "
									+ data_[i].villageName;
							//obj.find(divName).width(obj.find(inputName).width() * codeLevel);
						} else if (codeLevel == 5) {
							innerHtml = data_[i].cityName + " "
									+ data_[i].countyName + " "
									+ data_[i].townName + " "
									+ data_[i].villageName + " "
									+ data_[i].naturalVillageName;
							//obj.find(divName).width(obj.find(".select_txt").width() * codeLevel);
						}
						temp.html(innerHtml);
						obj.find(inputName).find(".select_con").append(temp);
						temp.hover(function() {
							changeToWhite(divName , obj);
							$(this).css('background-color', 'pink');
							highLightIndex = $(this).index();
						}, function() {
							$(this).css('background-color', 'white');
						});
						temp.click(function() {
							obj.find(inputName).find(".select_txt").attr("value","");
							reBuild(data_[highLightIndex], codeLevel , this);
							obj.find(divName).html('').hide();
							obj.find(inputName).find(".select_con").hide();
						});
						
					}
					//obj.find(inputName).find(".select_con").append(temp);
					$(obj).find(inputName).find(".select_con").show();
					
				}
				
				
				
			});
		}

		/**
		 * 处理键盘按下后弹起的事件
		 * 
		 */
		function processKeyup(inputName, divName, codeLevel , obj) {
			var myEvent = window.event || arguments.callee.caller.arguments[0];
			var keyCode = myEvent.keyCode;
			// 输入是字母，或者退格键则需要重新请求
			if ((keyCode >= 65 && keyCode <= 90) || keyCode == 8
					|| keyCode == 32 || (keyCode >= 48 && keyCode <= 58)) {
				highLightIndex = -1;
				// 处理上下键(up,down)
			} else if (keyCode == 38 || keyCode == 40) {
				processKeyUpAndDown(keyCode, inputName, divName , obj);
				// 按下了回车键
			} else if (keyCode == 13) {
				processEnter(inputName, divName, codeLevel ,  obj);
			}
		}

		/**
		 * 处理按下Enter键
		 */
		 function processEnter(inputName, divName, codeLevel , obj) {
				//回车按钮，有两种情况，第一种为模糊查询敲击回车，第二种为上下选择DIV，敲击回车
				if (highLightIndex != -1) {
					$(obj).find(inputName).val(obj.find(divName).children().eq(highLightIndex).html());
					$(obj).find(divName).html('').hide();
					reBuild(data_[highLightIndex], codeLevel , obj);
				} else {
					//模糊查询，需要获取各个层级文本框的文本值，作为查询条件去后台请求
					provinceName = $(obj).find('#provinceName').find(".select_txt").val();
					cityName = $(obj).find('#cityName').find(".select_txt").val();
					countyName = $(obj).find('#countyName').find(".select_txt").val();
					townName = $(obj).find('#townName').find(".select_txt").val();
					villageName = $(obj).find('#villageName').find(".select_txt").val();
					naturalVillageName = $(obj).find('#naturalVillageName').find(".select_txt").val();
					
					if (codeLevel == 4) {
						$(obj).find('#naturalVillageName').val("");
					} else if (codeLevel == 3) {
						$(obj).find('#naturalVillageName').val("");
						$(obj).find('#villageName').val("");
					} else if (codeLevel == 2) {
						$(obj).find('#naturalVillageName').val("");
						$(obj).find('#villageName').val("");
						$(obj).find('#townName').val("");
					} else if (codeLevel == 1) {
						$(obj).find('#naturalVillageName').val("");
						$(obj).find('#villageName').val("");
						$(obj).find('#townName').val("");
						$(obj).find('#countyName').val("");
					}
					processAjaxRequest(inputName, divName, codeLevel , obj);
				}

			}

		/**
		 * 处理按上下键的情况
		 */
		function processKeyUpAndDown(keyCode, inputName, divName , obj) {
			var words = $(divName).children();
			var num = words.length;
			if (num <= 0)
				return;
			changeToWhite(divName , obj);
			highLightIndex = ((keyCode != 38 ? num + 1 : num - 1) + highLightIndex)
					% num;
			words.eq(highLightIndex).css('background-color', 'pink');
			$(inputName).val(words.eq(highLightIndex).html());
		}

		/**
		 * 如果有高亮的则把高亮变白
		 */
		 function changeToWhiteObj(obj) {
				if (highLightIndex != -1) {
					obj.children().eq(highLightIndex).css(
							'background-color', 'white');
				}
			}
		function changeToWhite(divName , obj) {
			if (highLightIndex != -1) {
				$(divName).children().eq(highLightIndex).css(
						'background-color', 'white');
			}
		}
	</script>
</body>
</html>
